<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import * as echarts from "echarts";
import { debounce } from "lodash-es";
import { useResizeObserver } from "@vueuse/core";

const props = defineProps<{
  options?: echarts.EChartsCoreOption;
}>();

const emits = defineEmits<{
  init: [e: echarts.ECharts];
}>();

const refView = ref();

// echarts的实例不能赋值给响应式对象
let chartIns: any = undefined;

onMounted(() => {
  chartIns = echarts.init(refView.value);
  if (props.options) chartIns.setOption(props.options);
  emits("init", chartIns);
});

watch(
  () => props.options,
  (val) => {
    chartIns?.setOption(val);
  }
);

const debounceRender = debounce(() => chartIns?.resize(), 500);
useResizeObserver(refView, () => debounceRender());
</script>

<template>
  <div ref="refView"></div>
</template>
